package com.zsr.example.controller.front;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsr.example.config.exception.CommonJsonException;
import com.zsr.example.entity.TOrder;
import com.zsr.example.service.EduCourseService;
import com.zsr.example.service.TOrderService;
import com.zsr.example.service.TPayLogService;
import com.zsr.example.util.BusinessUtil;
import com.zsr.example.util.CommonUtil;
import com.zsr.example.util.JwtUtil;
import com.zsr.example.util.constants.ErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author zsr
 * @since 2021-12-06
 */
@RestController
@CrossOrigin
@RequestMapping("/orderservice/order")
public class TOrderController {
    @Autowired
    private TOrderService orderService;
    @Autowired
    private TPayLogService payService;
    @Autowired
    private EduCourseService courseService;

    /**
     * 根据课程id和用户id创建订单，返回订单id
     *
     * @param courseId
     * @param request
     * @return
     */
    @PostMapping("createOrder/{targetType}/{courseId}")
    public JSONObject save(@PathVariable Integer targetType, @PathVariable String courseId, HttpServletRequest request) {
        String id = JwtUtil.getMemberIdByJwtToken(request);//用户id
        if (StringUtils.isEmpty(id)) throw new CommonJsonException(ErrorEnum.E_20011);
        String orderId = orderService.saveOrder(targetType, courseId, JwtUtil.getMemberIdByJwtToken(request));
        return CommonUtil.successJson(orderId);

    }

    /**
     * 获取订单详情
     *
     * @param orderId
     * @return
     */
    @GetMapping("getOrder/{orderId}")
    public JSONObject get( @PathVariable String orderId) {
        TOrder order = orderService.getOne(new LambdaQueryWrapper<TOrder>()
                .eq(TOrder::getOrderNo, orderId));
        return CommonUtil.successJson(order);
    }

    /**
     * 获取当前登录用户的订单列表
     * @param status
     * @param request
     * @return
     */
    @GetMapping(value = {"getList/{status}", "getList/"})
    public JSONObject getList(@PathVariable(required = false) String status, HttpServletRequest request) {
        String memberId = JwtUtil.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) throw new CommonJsonException(ErrorEnum.E_20011);

        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId);
        if (!StringUtils.isEmpty(status)) queryWrapper.eq("status", status);
        List<TOrder> list = orderService.list(queryWrapper);
        return CommonUtil.successJson(list);

    }

    //------------------------分割线  payLog相关----------------------

    /**
     * 生成二维码
     *
     * @return
     */
    @GetMapping("/createNative/{orderNo}")
    public JSONObject createNative(@PathVariable String orderNo) {
        Map<String, Object> map = payService.createNative(orderNo);
        return CommonUtil.successJson(map);
    }


    /**
     * 查询微信订单支付状态
     *
     * @param orderNo
     * @return
     */
    @GetMapping("/queryPayStatus/{orderNo}")
    public JSONObject queryPayStatus(@PathVariable String orderNo) {
        //调用查询接口
        Map<String, String> map = payService.queryPayStatus(orderNo);
        if (ObjectUtils.isEmpty(map)) {
            return CommonUtil.errorJson();
        }
        if (!ObjectUtils.isEmpty(map.get("trade_state")) && map.get("trade_state").equals("SUCCESS")) {//如果成功
            //更改订单状态
            return updateOrder(map);
        }
        return CommonUtil.successPay();
    }

    private JSONObject updateOrder(Map<String, String> map) {
        TOrder tOrder = payService.updateOrderStatus(map);
        if (!ObjectUtils.isEmpty(tOrder)) {
            BusinessUtil.getBusService(tOrder.getTargetType()).updateBuyCount(tOrder.getTargetId());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        return CommonUtil.successJson(result);
    }

    /**
     * 生成支付宝二维码
     *
     * @param orderNo
     * @return
     */
    @GetMapping(value = "/createNativeByAlipay/{orderNo}")
    public JSONObject createNativeByAlipay(@PathVariable String orderNo) {
        Map<String, Object> map = payService.createNativeByAlipay(orderNo);
        return CommonUtil.successJson(map);
    }

    /**
     * 查询支付宝支付状态
     *
     * @param orderNo
     * @return
     */
    @GetMapping(value = "/queryPayStatusByAlipay/{orderNo}")
    public JSONObject queryPayStatusByAlipay(@PathVariable String orderNo) {
        Map<String, String> map = payService.queryPayStatusByAlipay(orderNo);
        if (ObjectUtils.isEmpty(map)) return CommonUtil.errorJson(ErrorEnum.E_30001);
        if (!ObjectUtils.isEmpty(map.get("trade_state")) && map.get("trade_state").equals("TRADE_SUCCESS")) {//如果成功
            //更改订单状态
            return updateOrder(map);
        }

        return CommonUtil.successPay();
    }
}

